import { computed, nextTick, onUnmounted, ref, watch } from 'vue'
import { useStore } from 'vuex'
import BScroll from '@better-scroll/core'
import Slide from '@better-scroll/slide'
BScroll.use(Slide)
export default function useMiniSlider () {
  const store = useStore()

  const sliderWrapperRef = ref()
  const slider = ref()

  const fullScreen = computed(() => store.state.fullScreen)
  const playlist = computed(() => store.state.playlist)
  const sliderShow = computed(() => !fullScreen.value && !!playlist.value)
  const currentIndex = computed(() => store.state.currentIndex)

  let sliderVal
  watch(sliderShow, async (newSliderShow) => {
    if (newSliderShow) {
      await nextTick()
      if (!sliderVal) {
        sliderVal = slider.value = new BScroll(sliderWrapperRef.value, {
          click: true,
          scrollX: true,
          scrollY: false,
          momentum: false,
          bounce: false,
          probeType: 2,
          slide: {
            autoplay: false,
            loop: true
          }
        })
        sliderVal.on('slidePageChanged', ({ pageX }) => {
          console.log('slidePageChanged', pageX)
          store.commit('setCurrentIndex', pageX)
          // 暂停时切歌
          // 点击返回按钮，也会触发slidePageChanged事件
          store.commit('setPlayingState', true)
        })
      } else {
        sliderVal.refresh()
      }
      //  mini播放器显示时，滚动到歌曲播放页
      // sliderVal.goToPage(currentIndex.value, 0, 0)
    }
  })
  // currentSong为空，可能是currentIndex不正确
  watch(currentIndex, (newIndex) => {
    console.log('watch currentIndex', newIndex)
    if (slider.value && sliderShow.value) {
      slider.value.goToPage(currentIndex.value, 0, 0)
    }
  })

  onUnmounted(() => {
    slider.value && slider.value.destroy()
  })
  return {
    slider,
    sliderWrapperRef
  }
}
